using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.IdentityModel.Tokens;
using NetDisk.Dtos;
using NetDisk.Models;
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Security.Claims;
using System.Text;

namespace NetDisk.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class AuthController : ControllerBase
    {
        private readonly ApplicationDbContext _dbContext;
        private readonly IConfiguration _config;

        public AuthController(ApplicationDbContext dbContext, IConfiguration config)
        {
            _dbContext = dbContext;
            _config = config;
        }

        [HttpPost("login")]
        public string Login(LoginDto loginDto)
        {
            var user = _dbContext.Users.Where(u => u.Name == loginDto.Name).FirstOrDefault();

            if (user != null && BCrypt.Net.BCrypt.Verify(loginDto.Password, user.Password))
            {
                var claims = new List<Claim>
                    {
                        new Claim(JwtRegisteredClaimNames.Sub, user.Id.ToString()),
                        new Claim(JwtRegisteredClaimNames.Iat, DateTimeOffset.Now.ToUnixTimeSeconds().ToString()),
                        new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
                    };

                var jwtKey = Encoding.UTF8.GetBytes(_config["jwt:key"]);
                var securityKey = new SymmetricSecurityKey(jwtKey);
                var signKey = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256);
                var jwt = new JwtSecurityToken(
                    issuer: _config["jwt:issuer"],
                    audience: _config["jwt:audience"],
                    claims: claims,
                    expires: DateTime.Now.AddDays(2),
                    notBefore: DateTime.Now,
                    signingCredentials: signKey
                    );

                return new JwtSecurityTokenHandler().WriteToken(jwt);
            }

            return string.Empty;
        }

        [Authorize]
        [HttpGet("check-login")]
        public string CheckLogin()
        {
            var userId = int.Parse(HttpContext.User.FindFirstValue(ClaimTypes.NameIdentifier));
            var user = _dbContext.Users
                .Where(u => u.Id == userId)
                .AsNoTracking()
                .FirstOrDefault();

            return user?.Name;
        }

        [Authorize]
        [HttpPut("change-password")]
        public int ChangePassword(ChangePasswordDto changePasswordDto)
        {
            var userId = int.Parse(HttpContext.User.FindFirstValue(ClaimTypes.NameIdentifier));
            var user = _dbContext.Users
                .Where(u => u.Id == userId)
                .FirstOrDefault();
            if (user != null && BCrypt.Net.BCrypt.Verify(changePasswordDto.Password, user.Password))
            {
                user.Password = BCrypt.Net.BCrypt.HashPassword(changePasswordDto.NewPassword);
                _dbContext.Users.Update(user);
                var result = _dbContext.SaveChanges();
                return result;
            }

            return 0;
        }
    }
}